<?php
// +--------------+------------------------+------+-----+---------+----------------+
// | Field        | Type                   | Null | Key | Default | Extra          |
// +--------------+------------------------+------+-----+---------+----------------+
// | id           | int(11)                | NO   | PRI | NULL    | auto_increment |
// | title        | varchar(60)            | YES  |     |         |                |
// | type         | varchar(15)            | YES  |     |         |                |
// | pc_cover_id  | int(11) unsigned       | YES  |     | 0       |                |
// | wap_cover_id | int(11) unsigned       | YES  |     | 0       |                |
// | status       | tinyint(1)             | YES  |     | 0       |                |
// | member_id    | int(11) unsigned       | YES  |     | 0       |                |
// | create_time  | int(11) unsigned       | YES  |     | 0       |                |
// | update_time  | int(11) unsigned       | YES  |     | 0       |                |
// | slug         | varchar(150)           | YES  |     |         |                |
// | link_url     | varchar(250)           | YES  |     |         |                |
// | open_target  | enum('_self','_blank') | YES  |     | _self   |                |
// | sort         | int(11)                | YES  |     | 0       |                |
// +--------------+------------------------+------+-----+---------+----------------+
namespace app\common\model;

use think\facade\Config;
use think\facade\Cache;
use app\common\model\Base;
use app\common\validate\Banner as Validate;

class Banner extends Base
{
    /**
     * 与AuthGroup BelongsTo关联设置
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @return   array              [description]
     */
    public function pcImage()
    {
        return $this->belongsTo('Upload', 'pc_cover_id')->bind([
                'pc_cover_path'  => 'save_path',
            ]);
    }

    /**
     * 列表搜索方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param     搜索参数
     * @param    integer            $page_rows 每页显示数量
     * @return   Paginate
     */
    public function minePaginate($param, $page_rows = 0)
    {
        if($page_rows < 1){
            $page_rows = Config::get('paginate.list_rows');
        }

        $map = $this->parseSearchParam($param);

        $config = [];
        $config["query"] = $param;
        // 分页参数名是 page ，paginate方法内有获取到该值的方法
        $page = 1;
        if(isset($param["page"])){
            $page = intval($param["page"]);
        }
        $config["page"] = $page;

        $order_type = 'default';
        if(isset($param['order'])){
            $order_type = $param['order'];
        }
        $order_str = $this->queryOrderStr($order_type);
        $paginate = $this->with('pc_image')->where($map)->order($order_str)->paginate($page_rows, false, $config);
        return $paginate;
    }

    /**
     *
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-22
     * @param    string             $type        Banner Type
     * @param    integer            $limit_count 0表示不限制返回数量
     * @return   array                           [description]
     */
    public function userTypeSelect($type, $limit_count = 0){
        $key_name = $this->typeCacheKey($type);
        $list = Cache::get($key_name);
        if(!empty($list)){
            // echo('read key name: '.$key_name);
            return $list;
        }

        $select_fields = [
            'id',
            'title',
            'pc_cover_id',
            'link_url',
            'open_target',
        ];
        $order_str = $this->queryOrderStr('default');

        $with_str = NULL;
        if($type == 'home'){
            $with_str = 'pc_image';
        }
        $list = $this->with($with_str)->field($select_fields)->where('type', $type)->where('status', 1)->order($order_str)->limit($limit_count)->select();
        if(!empty($list)){
            Cache::set($key_name, $list);
        }
        return $list;
    }

    /**
     * 添加或更新记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $data 表单提交数据
     * @param    integer            $id   主键ID
     * @return   array                    更新结果
     */
    public function createOrUpdate($data, $id = 0)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "添加或更新Banner失败"];
        if($id > 0){
            $data['id'] = $id;
        }

        $validate = new Validate;
        // 默认验证场景名
        $scene_name = 'home';
        if(isset($data['type']) && in_array($data['type'], ['home', 'link'])){
            $scene_name = $data['type'];
        }
        if(!$validate->scene($scene_name)->check($data)){
            $res['msg'] = $validate->getError();
            return $res;
        }

        if(isset($data['id']) && $data['id'] > 0){
            $item = $this->where('id', $data['id'])->find();
        }else{
            $item = [];
        }
        if(empty($item)){
            $is_update = false;
            $msg = '添加Banner成功';
        }else{
            $is_update = true;
            $msg = '更新Banner成功';
            $data['id'] = $item['id'];
        }
        $this->data($data)->isUpdate($is_update)->allowField(true)->save();
        $this->clearTypeCaches($data['type']);

        $res = [
            'status' => true,
            'msg' => $msg,
            'data' => ['id' => $this->id],
        ];
        return $res;
    }

    /**
     * 根据Banner标题创建/更新记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $data [description]
     * @return   array                    [description]
     */
    public function findOrCreate($data)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "添加或更新Banner失败"];

        $map = [];
        if(empty($data['title'])){
            $res['msg'] = 'Banner标题不能为空';
            return $res;
        }
        $map['title'] = $data['title'];
        $item = $this->where($map)->find();
        if(!empty($item)){
            $res = [
                'status' => true,
                'data' => ['id' => $item['id']],
                'msg' => '查找到该Banner记录',
            ];
            return $res;
        }

        return $this->createOrUpdate($data);
    }

    /**
     * 转化查询条件
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param [description]
     * @return   array                     [description]
     */
    private function parseSearchParam($param)
    {
        $map = [];
        foreach ($param as $key => $value) {
            if(!is_array($value)){
                $value = trim($value);
            }
            switch ($key) {
                case 'type':
                    $map[] = [$key, "like", $value];
                    break;
                case 'keyword':
                    if(empty($value)){
                        continue;
                    }else{
                        $keyword = "%{$value}%";
                    }
                    $map[] = ["title", "like", $keyword];
                    break;
            }
        }
        return $map;
    }

    /**
     * 排序后的操作
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-11
     * @return   boolean                   [description]
     */
    protected function afterResort(){
        $this->clearTypeCaches();
        return true;
    }

    /**
     * 删除记录后的执行方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-12
     * @param    array              $item [description]
     * @return   boolean                  [description]
     */
    protected function afterDeleteItem($item){
        // 清除缓存数据
        $this->clearTypeCaches();
        return true;
    }

    /**
     * 排序后的操作
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-11
     * @return   boolean                   [description]
     */
    private function clearTypeCaches($type = ''){
        if(is_array($type)){
            $list = $type;
        }else if(empty($type)){
            // type字段是保留类型
            $list = $this->field(array('type as banner_type'))->group('type')->select();
        }else{
            $list = ['banner_type' => $type];
        }
        foreach ($list as $key => $banner) {
            if(is_object($banner)){
                $key_name = $this->typeCacheKey($banner->banner_type);
            }else if(is_array($banner) && isset($banner['banner_type'])){
                $key_name = $this->typeCacheKey($banner['banner_type']);
            }else if(is_string($banner)){
                $key_name = $this->typeCacheKey($banner);
            }else{
                continue;
            }
            Cache::rm($key_name);
        }
        return true;
    }

    private function typeCacheKey($type){
        return "banner_top_{$type}";
    }

    /**
     * 搜索排序方式
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    string             $param 排序方式
     * @return   string                    [description]
     */
    protected function queryOrderStr($order_type = '')
    {
        return 'sort ASC, id DESC';
    }
}
